import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as apiLogin, logout as apiLogout, checkAuth as apiCheckAuth } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const isLoggedIn = ref(false)
  const isInitialized = ref(false)

  const login = async (credentials) => {
    try {
      const response = await apiLogin(credentials)
      if (response.success) {
        user.value = response.user
        isLoggedIn.value = true
        return response
      }
      throw new Error(response.message)
    } catch (error) {
      throw error
    }
  }

  const logout = async () => {
    try {
      await apiLogout()
    } catch (error) {
      // 即使API调用失败，也要清除本地状态
      console.log('登出API调用失败，但仍会清除本地状态')
    } finally {
      // 重置所有认证相关状态
      user.value = null
      isLoggedIn.value = false
      isInitialized.value = false
    }
  }

  // 初始化用户状态（检查是否已登录）
  const initializeAuth = async () => {
    if (isInitialized.value) return
    
    try {
      const response = await apiCheckAuth()
      if (response.success) {
        user.value = response.user
        isLoggedIn.value = true
      } else {
        user.value = null
        isLoggedIn.value = false
      }
    } catch (error) {
      // 如果检查失败（如401错误），清除状态
      // 这是正常情况，不需要打印错误日志
      user.value = null
      isLoggedIn.value = false
    } finally {
      isInitialized.value = true
    }
  }

  const checkAuth = () => {
    // 返回当前登录状态
    return isLoggedIn.value
  }

  // 重置初始化状态（用于重新检查认证）
  const resetAuthState = () => {
    isInitialized.value = false
    user.value = null
    isLoggedIn.value = false
  }

  return {
    user,
    isLoggedIn,
    isInitialized,
    login,
    logout,
    checkAuth,
    initializeAuth,
    resetAuthState
  }
})
